<?php

namespace App\Http\Controllers\Wechat;

use App\Models\Areas;
use App\Models\Category;
use App\Models\Goods;
use App\Models\NewAdmin;
use App\Models\ShopBanner;
use App\Models\ShopCategory;
use App\Models\ShopGoods;
use App\Models\ShopUser;
use App\Models\ShopApply;
use App\Models\ShopUserLog;
use App\Models\SaleUser;
use App\Models\MemberOther;
use App\Models\SaleLog;
use App\Models\ShopSms;
use App\Models\SaleUserLogin;
use App\Services\AlipayMiniAppService;
use App\Services\CommonService;
use App\Services\GoodsService;
use App\Services\AlipayService;
use App\Services\OtherCallbacksService;
use Illuminate\Http\Request;

class ShopController
{
    /**
     * 获取店铺轮播图
     */
    public function getShopBanner(Request $request){
        $member_id = $request->input('member_id');
        if($member_id){
            $data = ShopBanner::GetShopBannerByMemberid($member_id);
            if(!empty($data)){
                foreach ($data as $k=>$v){
                    if($v['status'] != GoodsService::GOODS_STATUS_PUT){ //商品未上架  goods_id置空 不让跳转
                        $data[$k]['goods_id'] = '';
                    }
                }
            }else{
                $data[0] = ['banner_img'=>'20220408095259.jpg','goods_id'=>''];
            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '店铺不存在');
        }
    }

    /**
     * 获取商户是否开启城市定位
     */
    public function getShopCityLocation(Request $request){
        $member_id = $request->input('member_id');
        if($member_id){
            $is_city_location = ShopUser::where('member_id',$member_id)->value('is_city_location');
            $data['is_city_location'] = $is_city_location;
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '店铺不存在');
        }
    }


    /**
     * 获取店铺分类
     */
    public function getShopCategory(Request $request){
        $member_id = $request->input('member_id');
        if($member_id){
            $data = ShopCategory::where([['member_id',$member_id],['status',ShopCategory::SHOP_CATEGORY_STATUS_ENABLE],['is_delete',ShopCategory::SHOP_CATEGORY_DELETE_NO]])->select('id','cat_name')->orderBy('sort', 'ASC')->get();
            $data = $data ? $data->toArray() : [];
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '店铺不存在');
        }
    }

    /**
     * 获取商户店铺首页商品信息
     */
    public function getShopIndex(Request $request){
        $member_id = $request->input('member_id');
        $city_name = $request->input('city_name');
        $goods_name = $request->input('goods_name');
        $sort_data = $request->input('sort_data',GoodsService::GOODS_SORT_COMPREHENSIVE);
        $page = $request->input('page');
        $pageSize = $request->input('pageSize');
        if($member_id){
            $is_city_location = ShopUser::where('member_id',$member_id)->value('is_city_location');
            if($is_city_location == ShopUser::SHOP_USER_CITY_LOCATION_OPEN){//开启城市定位
                $city_id = Areas::where([['name','like','%'.$city_name.'%'],['level',2]])->value('id');
                if($city_id){
                    $where[] = ['show_ity',$city_id];
                }
            }
            $where[] = ['status',GoodsService::GOODS_STATUS_PUT];
            $where[] = ['is_delete',CommonService::GOODS_IS_DELETE_NOT];
            $where[] = ['member_id',$member_id];
            if(!empty($goods_name)){
                $where[] = ['title','like','%'.$goods_name.'%'];
            }
            $orderby = GoodsService::GOODS_SORT_TYPE_NAME_LIST[$sort_data];
            $upanddown = GoodsService::GOODS_SORT_UP_DOWN_LIST[$sort_data];
            $goods = Goods::where($where)->select('id','title','rent_label','imgurl','min_price','min_lease_term','is_huabei')->orderBy($orderby,$upanddown)->paginate($pageSize);
            $goods = $goods ? $goods->toArray() : [];
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $goods);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '店铺不存在');
        }
    }

    /**
     * 根据分类id获取商户商品
     */
    public function getShopGoods(Request $request){
        $member_id = $request->input('member_id');
        $cate_id = $request->input('cate_id');
        $goods_name = $request->input('goods_name');
        $sort_data = $request->input('sort_data',GoodsService::GOODS_SORT_COMPREHENSIVE);
        $page = $request->input('page');
        $pageSize = $request->input('pageSize');
        if($member_id){
            $where[] = ['g.status',GoodsService::GOODS_STATUS_PUT];
            $where[] = ['g.is_delete',CommonService::GOODS_IS_DELETE_NOT];
            $where[] = ['g.member_id',$member_id];
            if(!empty($goods_name)){
                $where[] = ['g.title','like','%'.$goods_name.'%'];
            }
            if(!empty($cate_id)){
                $where[] = ['s.cat_id',$cate_id];
            }
            $orderby = 'g.'.GoodsService::GOODS_SORT_TYPE_NAME_LIST[$sort_data];
            $upanddown = GoodsService::GOODS_SORT_UP_DOWN_LIST[$sort_data];
            $goods = ShopGoods::from('sp_shop_goods as s')->leftjoin('sp_goods_2 as g','s.goods_id','g.id')->where($where)->select('g.id','g.title','g.rent_label','g.imgurl','g.min_price','g.min_lease_term','g.is_huabei')->orderBy($orderby,$upanddown)->paginate($pageSize);
            $goods = $goods ? $goods->toArray() : [];
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $goods);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '店铺不存在');
        }
    }


    //获取客服电话
    public function getTelePhone(Request $request){
        $member_id = $request->input('member_id');
        if(!empty($member_id)){
            $data['shop_mobile'] = ShopUser::where('member_id',$member_id)->value('mobile');
        }
        $data['platform_mobile'] = config('alipay.Telephone');
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }


    /***
     * 供应商入驻信息获取
     */
    public function getSupplierData(){
        $category = Category::where([['parentid',0],['is_delete',Category::CATEGORY_NOT_DELETE],['enabled',Category::CATEGORY_STATUS_DISPLAY]])->select('id','name')->get();
        $data['category'] = obToArray($category);
        $data['fap_type'] = ShopUser::FAPTYPE_LIST;
        $data['account_type'] = ShopUser::ACCOUNT_TYPE_LIST;
        $data['risk_type'] = ShopUser::SHOP_RISK_LIST;
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    /**
     * 获取城市列表
     */
    public function getAreas()
    {
        $data = Areas::GetAreasList();
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    /**
     * 小程序供应商申请
     */
    public function supplierApply(Request $request){
        $input = $request->input();
        $miniId = AlipayMiniAppService::getInstance()->getMiniId();
        if (empty($input['name']) || empty($input['mobile']) || empty($input['area']) || empty($input['product'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少参数');
        }

        //验证
        $alipay_data1= [];
        $alipay_data1['app_name'] = '****app_personal_information';
        $alipay_data1['content'] = $input['name'];
        $prequery1 = AlipayService::securityRiskText($miniId, $alipay_data1);

        $alipay_data2= [];
        $alipay_data2['app_name'] = '****app_personal_information';
        $alipay_data2['content'] = $input['mobile'];
        $prequery2 = AlipayService::securityRiskText($miniId, $alipay_data2);

        $alipay_data3= [];
        $alipay_data3['app_name'] = '****app_personal_information';
        $alipay_data3['content'] = $input['area'];
        $prequery3 = AlipayService::securityRiskText($miniId, $alipay_data3);

        $alipay_data4= [];
        $alipay_data4['app_name'] = '****app_personal_information';
        $alipay_data4['content'] = $input['product'];
        $prequery4 = AlipayService::securityRiskText($miniId, $alipay_data4);

        //var_dump($prequery);
        if(!$prequery1['status'] || !$prequery2['status'] || !$prequery3['status'] || !$prequery4['status']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, CommonService::HTTP_CODE_MESSAGE);
        }


        $shopUser = ShopApply::where('mobile',$input['mobile'])->first();
        if (!empty($shopUser)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '该手机号码已经存在,请重新输入');
        }

        $time = time();
        $addData = array(
            'name' => $input['name'], //名称
            'mobile' => $input['mobile'], //电话
            'area' => $input['area'], //地区
            'product' => $input['product'], //产品
            'remark' => '暂无备注', //备注
            'create_at' => $time,
        );
        $res = ShopApply::insert($addData);
        if ($res) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '提交成功，请等待平台审核');
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '提交失败，请稍后再试或联系平台客服');
        }
    }


    //商家入驻推广平台
    public function shopApply(Request $request)
    {
        $input = $request->input();
        $mobile = $input['mobile'];
        $name = $input['name'];
        $shopName = $input['shop_name'];
        $shopAdress = $input['shop_address'];

        $sale_user_id = date('YmdHis').mt_rand(10,99);
        $code = '102810465316';
        $addData = array(
            'sale_user_id'=>$sale_user_id,//经销商ID
            'parent_user_id' => $code, //父级ID
            'rate_money'=>SaleUser::SALE_USER_MONEY, //固定金额
            'rate_type'=>SaleUser::RATE_MONEY,//固定租期结算
            'people' => $name, //联系人
            'contact_tel' => $mobile, //联系人手机号
            'user_type' => '1', //1企业/2个人
            'level' => SaleUser::LEVEL_TWO, //分销商级别
            'faname' => $name, //法人/个人姓名
            'idcard' => '', //法人/个人身份证号
            'faidcard' => '', //法人/个人身份证正面
            'faidcard_back' => '', //法人/个人身份证反面(带国徽的一面)
            'address'=>$shopAdress,//地址
            'mechanism'=>$shopName,//公司名称
            'shopcity' => '全国', //当前经营位置 省-市
            'create_time'=>date('Y-m-d H:i:s'), // 入驻时间
            'update_time'=>date('Y-m-d H:i:s'), // 修改时间
            'is_show' => CommonService::SHOP_ENABLE, //是否启用 1启用SHOP_ENABLE2不启用SHOP_DISABLE
            'code' => invitation_no(),//邀请码
            'is_check' => CommonService::SHOP_ENABLE, //是否审核1审核2待审核
            'end_time' =>date('Y-m-d H:i:s',time()+365*24*3600), //失效时间365天后
            'balance'=>0, // 账户余额
            'balance_end'=>0, // 账户冻结余额
            'type'=>SaleUser::SALE_ALIPAY, //1线上2线下
            'balance_drawal'=>0, // 正在提现金额-冻结金额
        );
        //添加推广人员
        $sale_user = SaleUser::where('contact_tel',$mobile)->first();
        $sale_user = $sale_user ? $sale_user->toArray() : [];
        if(empty($sale_user)){
            $id = SaleUser::insertGetId($addData);
            if ($id) {
                //添加账号
                $userData = array(
                        'sale_user_id'=>$sale_user_id,
                        'username'=>$shopName, //用户名/昵称
                        'password'=>md5($mobile.'txz'.$mobile), // 密码
                        'mobile'=>$mobile, //手机号码
                        'is_show'=>CommonService::SHOP_DISABLE, //是否启用1启用2不启用
                        'role'=>CommonService::SALE_ALL,//角色 1总账号2子账号
                        'create_time'=>date('Y-m-d H:i:s'),//创建时间

                    );
                $res = SaleUserLogin::insertGetId($userData);
                if($res){

                    //添加操作记录
                    $data = [];
                    $data['sale_user_id'] = $sale_user_id;
                    $data['user_id'] = $id;
                    $data['content'] = '商铺'.$shopName.'入驻推广';
                    $data['remark'] = '';
                    SaleLog::addLog($data);

                    //发短信
                    ShopSms::saleAlipayRegister($mobile,$sale_user_id);

                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '申请成功');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '提交失败，请稍后再试或联系平台客服.');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '申请失败，请稍后再试或联系平台客服');
            }
        }

    }

    /**
     * 小程序供应商申请
     */
    // public function supplierApply(Request $request){
    //     $input = $request->input();
    //     if (empty($input['shopname']) || empty($input['photo']) || empty($input['shoptype']) || empty($input['people']) || empty($input['contact_tel'])
    //         || empty($input['faptype']) || empty($input['mechanism']) || empty($input['companyid']) || empty($input['company_area']) || empty($input['company'])
    //         || empty($input['shopcity']) || empty($input['shopcard']) || empty($input['doorphoto']) || empty($input['seal_url']) || empty($input['faname'])
    //         || empty($input['idcard']) || empty($input['faidcard']) || empty($input['faidcard_back']) || empty($input['area_id'])) {
    //         return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少参数');
    //     }
    //     $shopUser = ShopUser::GetShopUser(array('shopname' => $input['shopname']));
    //     if (!empty($shopUser)) {
    //         return ReturnMsg(CommonService::HTTP_CODE_FAIL, '该店铺名称重复,请重新输入');
    //     }
    //     if (!Verify_Phone($input['contact_tel'])) {
    //         return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入有效手机号');
    //     } else {
    //         if(ShopUser::where('shopname',$input['shopname'])->count() > 0){
    //             return ReturnMsg(CommonService::HTTP_CODE_FAIL, '店铺名称已存在');
    //         }
    //     }
    //     if (!isBusinessRegistrationNumber($input['companyid'])) {
    //         return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入有效工商注册号');
    //     }
    //     if (!check_passportid($input['idcard'])) {
    //         return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入有效法人身份证号');
    //     }
    //     $time = time();
    //     $addData = array(
    //         'shopname' => $input['shopname'], //店铺名称
    //         'photo' => $input['photo'], //店铺头像
    //         'shoptype' => $input['shoptype'], //商品类型
    //         'people' => $input['people'], //联系人
    //         'contact_tel' => $input['contact_tel'], //联系人手机号
    //         'mobile' => $input['contact_tel'], //联系人手机号
    //         'faptype' => $input['faptype'], //发票类型：1普通发票  2增值税发票  1,2普通发票+增值税发票
    //         'mechanism' => $input['mechanism'], //公司/机构名称
    //         'companyid' => $input['companyid'], //工商/营业执照注册号
    //         'company_area' => $input['company_area'], //公司所在区域 省-市-区
    //         'area_id' => $input['area_id'], //区域城市id
    //         'company' => $input['company'], //公司地址
    //         'shopcity' => $input['shopcity'], //当前经营位置 省-市
    //         'shopcard' => $input['shopcard'], //营业执照图片
    //         'doorphoto' => $input['doorphoto'], //公司门头照
    //         'seal_url' => $input['seal_url'], //公章图片
    //         'faname' => $input['faname'], //法人姓名
    //         'idcard' => $input['idcard'], //法人身份证号
    //         'faidcard' => $input['faidcard'], //法人身份证图片
    //         'faidcard_back' => $input['faidcard_back'], //法人身份证图片(带国徽的一面)
    //         'category_id' => $input['shoptype'], //申请品类父级id
    //         'member_id' => $time,
    //         'shop_balance' => 0,
    //         'frozen_amount' => 0,
    //         'last_login_ip' => getRealIp(),
    //         'addtime' => $time,
    //     );
    //     //有三方关联ID进行数据绑定
    //     if(isset($input['relationId']) && $input['relationId']){
    //         $addData['relation_id'] = $input['relationId'];
    //     }
    //     $res = ShopUser::addData($addData);
    //     if ($res) {
    //         //添加操作记录
    //         ShopUserLog::addLog(0, $time, 2, '供应商入驻', [], [], '申请入驻成为产品供应商');
    //         //有三方关联ID进行回调操作
    //         if(isset($input['relationId']) && $input['relationId']){
    //             OtherCallbacksService::shopCreateNotify($time,$input['relationId']);
    //         }
    //         return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '提交成功，请等待平台审核');
    //     } else {
    //         return ReturnMsg(CommonService::HTTP_CODE_FAIL, '提交失败，请稍后再试或联系平台客服');
    //     }
    // }



}
